package io.adrainty.algorithm.mars;

/**
 * 数字字符串格式化
 * @link <a href="https://www.marscode.cn/practice/364l85wv6oo6lq?problem_id=7424418560930512940">...</a>
 * @author AdRainty
 * @version V1.0.0
 * @since 2024/11/21 下午9:35
 */
public class Solution003 {

    private Solution003() {}

    public static String solution(String s) {
        // write code here
        StringBuilder sb = new StringBuilder();
        int current = 0;
        // 去除前导0
        while (s.charAt(current) == '0') current++;
        if (current != 0) s = s.substring(current);

        String[] split = s.split("\\.");
        // 排除0.xxxxx的情况
        if ("".equals(split[0])) {
            sb.append("0");
        } else {
            int l = split[0].length();
            for (int i = l - 1; i >= 0; i--) {
                if (i != l - 1 && (l - i - 1) % 3 == 0) sb.append(',');
                sb.append(split[0].charAt(i));
            }
            sb.reverse();
        }

        if (split.length == 2) {
            sb.append(".").append(split[1]);
        }
        return sb.toString();
    }

}
